package com.air.ota.service.imp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.air.common.exception.WrongFormatException;
import com.air.common.service.imp.BaseServiceImp;
import com.air.common.util.QueryCondition;
import com.air.common.util.QueryExpression;
import com.air.ota.dao.BalanceTaskDao;
import com.air.ota.mo.BalanceTask;
import com.air.ota.mo.BalanceTaskDetail;
import com.air.ota.mo.EpayBalanceInfo;
import com.air.ota.service.IBalanceTaskDetailService;
import com.air.ota.service.IBalanceTaskService;
import com.air.ota.service.IEpayBalanceInfoService;
import com.air.ota.util.ConfigProperties;

@Service("balanceTaskService")
public class BalanceTaskServiceImp extends BaseServiceImp implements
		IBalanceTaskService, InitializingBean {
	
	@Autowired
	BalanceTaskDao balanceTaskMapper;
	@Autowired
	IEpayBalanceInfoService epayBalanceInfoService;
	@Autowired
	IBalanceTaskDetailService balanceTaskDetailService;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		this.baseDao  = balanceTaskMapper;
	}

	@Override
	//@Scheduled(cron = "0/0 0 3 * * *")
	public void checkTask() throws Exception{
		System.out.println("-----------------Check Balance Task-------------------");
		QueryCondition condition = new QueryCondition();
		condition.addQueryCondition("status", 0, QueryExpression.EQUALS);
		condition.addQueryCondition("executeDate", System.currentTimeMillis(), QueryExpression.LT);
		List<BalanceTask> tasks= this.queryByCondition(condition);
		
		if (tasks==null) return;
		
		for(BalanceTask task:tasks){
			processTask(task);
		}
		
	}
	
	private void processTask(BalanceTask task){
		int status = 1;
		task.setStatus(status);
		task.setDescCn(BalanceTask._STATUS_DESC.get(status));
		this.updateById(task);
		
		//step1 parse epay balance file
		File epay_balance_file = new File(ConfigProperties.getInstance().getValue("balance.epay.dir")+"/"+
					ConfigProperties.getInstance().getValue("epay.merchantId")+"_"+task.getCode());
		if (!epay_balance_file.exists()){//没有找到翼支付对账文件
			System.out.println("Couldn't Find Epay Balance File"+epay_balance_file.getPath());
			status = -100;
			task.setStatus(status);
			task.setDescCn(BalanceTask._STATUS_DESC.get(status));
			this.updateById(task);
			return;
		}
		List<EpayBalanceInfo> epayBalanceInfoList = parseEpayBalanceFile(epay_balance_file);
		
		
		
		//step2 import epay balance info into epay_balance_info 
		for(EpayBalanceInfo epayBalanceInfo:epayBalanceInfoList){
			try{
				epayBalanceInfoService.insert(epayBalanceInfo);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		//step3 download szt balance file from szt ftp
		File sztBalanceFile=null;
		
		//step4 parse szt balance file
		List<BalanceTaskDetail> detailList =parseSZTBalanceFile(sztBalanceFile);
		
		
		//step5 check each szt_balance_info,find relative record in  ota_system and epay_balance_info
		for(BalanceTaskDetail detail:detailList){
			processBalanceDetail(detail);
		}
		
	}
	
	
	private void processBalanceDetail(BalanceTaskDetail detail){
		try {
			boolean foundDepositTrans=false;
			boolean balancedDepositTrans=false;
			boolean foundEpayBalanceInfo=false;
			boolean balancedEpayBalanceInfo = false;
			//find deposit_trans in db
			
			//find balance info in epaybalance
			
			
			
			balanceTaskDetailService.insert(detail);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private List<BalanceTaskDetail> parseSZTBalanceFile(File balanceFile){
		List<BalanceTaskDetail> detailList=new ArrayList<BalanceTaskDetail>();
		
		try{
			RandomAccessFile file = new RandomAccessFile(balanceFile.getPath(),"r");
			String line = file.readLine();
			while(line!=null){
				line=line.trim();
				BalanceTaskDetail detail = new BalanceTaskDetail();
				try{
					detail.parse(line);
				}catch(WrongFormatException wfEx){
					wfEx.printStackTrace();
					line = file.readLine();
					continue;
				}
				line = file.readLine();
			}
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
		return detailList;
	}
	
	private List<EpayBalanceInfo> parseEpayBalanceFile(File balanceFile){
		List<EpayBalanceInfo> epayBalanceInfoList=new ArrayList<EpayBalanceInfo>();
		
		try {
			RandomAccessFile file = new RandomAccessFile(balanceFile.getPath(),"r");
			String line = file.readLine();
			while(line!=null){
				line = line.trim();
				EpayBalanceInfo info = new EpayBalanceInfo();
				try{
					info.parse(line, balanceFile.getPath());
				}catch(WrongFormatException wfEx){
					wfEx.printStackTrace();
					line = file.readLine();
					continue;
				}
				epayBalanceInfoList.add(info);
				line = file.readLine();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		return epayBalanceInfoList;
	}
	
}
